"""
隐患追踪管理数据模型

此模块定义了隐患追踪管理系统的数据模型，用于管理和跟踪C级和D级矿山的整改任务。
"""

from django.db import models
from django.utils import timezone
from datetime import datetime, timedelta
import json
from evaluationmine.models import SafetyEvaluation


class HazardTracking(models.Model):
    """
    隐患追踪主表
    
    用于记录和管理矿山安全评价中发现的隐患整改任务
    """
    
    # 整改状态选择
    STATUS_CHOICES = [
        ('待整改', '待整改'),
        ('整改中', '整改中'),
        ('整改完成', '整改完成'),
        ('复核通过', '复核通过'),
    ]
    
    # 安全等级选择
    SAFETY_LEVEL_CHOICES = [
        ('C级(一般)', 'C级(一般)'),
        ('D级(较差)', 'D级(较差)'),
    ]

    # 基本信息字段
    task_id = models.CharField('任务编号', max_length=50, unique=True, primary_key=True, help_text='系统唯一编号，如 HX20251009-001')
    mine_name = models.CharField('矿山名称', max_length=200, help_text='所属矿山名称')
    indicator_name = models.CharField('指标名称', max_length=200, help_text='触发整改的具体指标，如"支护设备完好率"')
    safety_level = models.CharField('安全等级', max_length=20, choices=SAFETY_LEVEL_CHOICES, help_text='危险等级')
    trigger_condition = models.CharField('触发条件', max_length=500, help_text='指标触发整改的条件，如"完好率 < 0.6"')
    remediation_suggestion = models.TextField('整改建议', help_text='对应模板生成的整改内容')
    
    # 责任人和状态信息
    responsible_person = models.CharField('责任人', max_length=100, help_text='执行整改的人员姓名或岗位')
    status = models.CharField('整改状态', max_length=20, choices=STATUS_CHOICES, default='待整改', help_text='任务状态')
    
    # 时间字段
    assigned_date = models.DateTimeField('指派日期', auto_now_add=True, help_text='系统生成任务的时间')
    deadline_date = models.DateTimeField('截止日期', help_text='规定整改完成时间')
    completion_date = models.DateTimeField('完成日期', null=True, blank=True, help_text='实际完成整改时间')
    
    # 附件和复核信息
    attachments = models.JSONField('附件', default=list, blank=True, help_text='上传的整改材料（照片、报告等）')
    remediation_image = models.ImageField('整改图片', upload_to='hazard_remediation_images/', null=True, blank=True, help_text='整改完成后的现场图片，每个隐患只能上传一张')
    reviewer = models.CharField('复核人', max_length=100, blank=True, help_text='复核人员姓名')
    review_comment = models.TextField('复核意见', blank=True, help_text='复核结果或意见')
    remarks = models.TextField('备注', blank=True, help_text='其他说明')
    
    # 关联到原始评价记录
    safety_evaluation = models.ForeignKey(
        SafetyEvaluation, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True, 
        verbose_name='关联安全评价', 
        help_text='关联的安全评价记录，隐患来源于此评价报告'
    )
    
    # 元数据字段
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '隐患追踪'
        verbose_name_plural = '隐患追踪'
        db_table = 'hazard_tracking'
        ordering = ['-assigned_date']

    def save(self, *args, **kwargs):
        """保存时自动生成任务编号"""
        if not self.task_id:
            # 生成任务编号：HX + 日期 + 序号
            today = datetime.now().strftime('%Y%m%d')
            count = HazardTracking.objects.filter(
                task_id__startswith=f'HX{today}'
            ).count()
            self.task_id = f'HX{today}-{count + 1:03d}'
        
        # 如果状态更新为"整改完成"且没有完成日期，自动设置完成日期
        if self.status == '整改完成' and not self.completion_date:
            self.completion_date = timezone.now()
        
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.task_id} - {self.mine_name} - {self.indicator_name}"
    
    def is_overdue(self):
        """检查是否已逾期"""
        if self.status in ['整改完成', '复核通过']:
            return False
        return timezone.now() > self.deadline_date
    
    def days_remaining(self):
        """计算剩余天数"""
        if self.status in ['整改完成', '复核通过']:
            return 0
        delta = self.deadline_date - timezone.now()
        return max(0, delta.days)
    
    def get_status_display_class(self):
        """获取状态显示样式类"""
        status_classes = {
            '待整改': 'status-pending',
            '整改中': 'status-progress',
            '整改完成': 'status-completed',
            '复核通过': 'status-verified',
        }
        return status_classes.get(self.status, 'status-pending')
    
    def get_safety_level_display_class(self):
        """获取安全等级显示样式类"""
        if 'C级' in self.safety_level:
            return 'level-warning'
        elif 'D级' in self.safety_level:
            return 'level-danger'
        return 'level-default'
    
    def add_attachment(self, file_info):
        """添加附件信息"""
        if not isinstance(self.attachments, list):
            self.attachments = []
        
        attachment = {
            'file_name': file_info.get('file_name', ''),
            'file_path': file_info.get('file_path', ''),
            'file_size': file_info.get('file_size', 0),
            'upload_time': timezone.now().isoformat(),
            'description': file_info.get('description', '')
        }
        self.attachments.append(attachment)
        self.save(update_fields=['attachments'])
    
    def get_attachments_info(self):
        """获取附件信息列表"""
        if not self.attachments:
            return []
        return self.attachments
    
    def get_evaluation_info(self):
        """获取关联的安全评价信息"""
        if not self.safety_evaluation:
            return None
        return {
            'evaluation_id': self.safety_evaluation.evaluation_id,
            'evaluation_date': self.safety_evaluation.evaluation_date.strftime('%Y-%m-%d'),
            'evaluator_name': self.safety_evaluation.evaluator_name,
            'region': self.safety_evaluation.get_region_display(),
            'evaluation_category': self.safety_evaluation.get_evaluation_category_display(),
            'safety_level': self.safety_evaluation.get_safety_level(),
            'comprehensive_score': self.safety_evaluation.calculate_comprehensive_score(),
        }
    
    @property
    def evaluation_id(self):
        """向后兼容的evaluation_id属性"""
        return self.safety_evaluation.evaluation_id if self.safety_evaluation else None
    
    @classmethod
    def get_statistics(cls):
        """获取隐患追踪统计信息"""
        total_count = cls.objects.count()
        pending_count = cls.objects.filter(status='待整改').count()
        progress_count = cls.objects.filter(status='整改中').count()
        completed_count = cls.objects.filter(status='整改完成').count()
        verified_count = cls.objects.filter(status='复核通过').count()
        overdue_count = cls.objects.filter(
            deadline_date__lt=timezone.now(),
            status__in=['待整改', '整改中']
        ).count()
        
        return {
            'total_count': total_count,
            'pending_count': pending_count,
            'progress_count': progress_count,
            'completed_count': completed_count,
            'verified_count': verified_count,
            'overdue_count': overdue_count,
        }
    
    @classmethod
    def create_from_evaluation_report(cls, safety_evaluation, low_score_indicators, remediation_suggestions):
        """
        从安全评价报告创建隐患追踪任务
        
        Args:
            safety_evaluation: 安全评价实例 (SafetyEvaluation对象)  
            low_score_indicators: 低分指标列表
            remediation_suggestions: 整改建议列表
        
        Returns:
            list: 创建的隐患追踪任务列表
        """
        created_tasks = []
        
        for suggestion in remediation_suggestions:
            # 设置截止日期为指派日期后7天
            deadline = timezone.now() + timedelta(days=7)
            
            # 根据安全等级确定等级
            safety_level = 'D级(较差)' if suggestion.get('安全等级') == '危险' else 'C级(一般)'
            
            task = cls.objects.create(
                mine_name=safety_evaluation.mine_name,
                indicator_name=suggestion.get('指标名称', ''),
                safety_level=safety_level,
                trigger_condition=suggestion.get('触发条件', ''),
                remediation_suggestion=suggestion.get('建议内容', ''),
                responsible_person='待指派',  # 默认值，后续可以更新
                deadline_date=deadline,
                safety_evaluation=safety_evaluation,
                remarks=f'由安全评价报告自动生成（评价编号: {safety_evaluation.evaluation_id}）'
            )
            created_tasks.append(task)
        
        return created_tasks

